package net.huashitong.gradePoint.service;

import com.ckfinder.connector.ServletContextFactory;
import com.sirdc.modules.core.config.Global;
import com.sirdc.modules.core.dao.BaseDao;
import com.sirdc.modules.sys.base.StringPKService;
import com.sirdc.modules.sys.entity.SysFile;
import com.sirdc.modules.sys.service.SysTableService;
import com.sirdc.modules.utils.UUIDGenerator;
import com.sirdc.modules.utils.date.DateUtils;
import com.sirdc.modules.utils.file.FileUtils;
import jodd.io.FileUtil;
import net.huashitong.gradePoint.dao.SysBnpFileDao;
import net.huashitong.gradePoint.entity.SysBnpFile;
import net.huashitong.gradePoint.filter.SysBnpFileFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
public class SysBnpFileService extends StringPKService<SysBnpFile> {

    @Autowired
    private SysBnpFileDao dao;
    @Autowired
    private SysTableService tableService;

    public SysBnpFileService() {
    }

    protected BaseDao<SysBnpFile, String> getDao() {
        return this.dao;
    }

    protected void beforeSave(SysBnpFile obj) {
        obj.setSysId(this.tableService.updateMaxSysId("t_sys_bnp_file", (String)null));
    }

    public List<SysFile> query(SysBnpFileFilter filter) {
        return this.dao.query(filter);
    }

    public void saveFile(SysBnpFile sysFile, MultipartFile file) throws Exception {
        String originalFilename = file.getOriginalFilename();
        String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String baseDirectory = Global.getUploadBaseDir();
        String filename = System.currentTimeMillis() + UUIDGenerator.randomBase62(5);
        String relativeDirectory = DateUtils.getDate("yyyy/MM/dd/");
        String relativeFilePath = relativeDirectory + filename + "." + fileType;
        String absoluteDirectory = baseDirectory + relativeDirectory;
        String absoluteFilePath = baseDirectory + relativeFilePath;
        FileUtils.createDirectory(FileUtils.path(absoluteDirectory));
        FileUtil.writeBytes(absoluteFilePath, file.getBytes());
        String baseUserUri = "/" + Global.USER_DIR + "/";
        String rootPath = ServletContextFactory.getServletContext().getContextPath();
        if(rootPath.length() == 1) {
            rootPath = "";
        }

        sysFile.setFilename(filename);
        sysFile.setFileType(fileType);
        sysFile.setUrl(baseUserUri + relativeFilePath);
        this.save(sysFile);
    }
}